<template>
  <div class="app-container">
    <el-card>
      <div slot="header">
        <el-search-form @search="onSearch" @reset="onReset">
          <el-form-item label="账号">
            <el-input
              clearable
              size="small"
              v-model="searchBody.loginName"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属角色">
            <el-select size="small" v-model="searchBody.roleId">
              <el-option
                v-for="item in roleIdOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-search-form>
      </div>
      <div>
        <el-button size="small" type="primary" @click="handleClick('add')"
          >新增</el-button
        >
      </div>
      <div class="have-pagination-container">
        <el-table v-loading="loading.list" :data="list" border>
          <el-table-column label="ID" prop="id" width="100"></el-table-column>
          <el-table-column label="账号" prop="loginName"></el-table-column>
          <el-table-column label="姓名" prop="name"></el-table-column>
          <el-table-column label="手机号" prop="phone"></el-table-column>
          <!--          <el-table-column
            label="开户名称"
            prop="companyName"
          ></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>-->
          <el-table-column label="角色" prop="roleName"></el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column
            label="最后登录时间"
            prop="createDate"
          ></el-table-column>
          <el-table-column label="是否启用" align="center" width="180">
            <template slot-scope="scope">
              <el-switch
                style="display: block"
                v-model="scope.row.status"
                active-value="1"
                inactive-value="2"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="启用"
                inactive-text="冻结"
                @change="onSwitchChange($event, scope.row)">
              </el-switch>

            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleClick('resetPwd', scope.row)"
                >重置密码</el-button
              >
              <!-- <el-button
                type="text"
                size="small"
                @click="handleClick('authSet', scope.row)"
                >权限配置</el-button
              > -->
              <el-button
                type="text"
                size="small"
                @click="handleClick('update', scope.row)"
                >修改</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="handleClick('remove', scope.row)"
                >删除</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="handleClick('setRegion', scope.row)"
                >区域设置</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-box">
        <el-pagination
          small
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-sizes="pageSizeOpts"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      :close-on-click-modal="false"
      :title="handleType == 'add' ? '新增' : '修改'"
      :visible.sync="updateDialog"
      width="50%"
    >
      <el-form
        ref="updateForm"
        :model="updateForm"
        :rules="updateFormRule"
        label-width="120px"
      >
        <el-form-item label="账号" prop="loginName">
          <el-input
            v-model="updateForm.loginName"
            class="el-input__medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="成员姓名" prop="name">
          <el-input
            v-model="updateForm.name"
            class="el-input__medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="updateForm.phone"
            class="el-input__medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属角色" prop="roleId">
          <el-select v-model="updateForm.roleId">
            <el-option
              v-for="item in roleIdOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <template v-if="handleType == 'add'">
          <el-form-item label="登录密码" prop="password">
            <el-input
              v-model="updateForm.password"
              class="el-input__medium"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="password2">
            <el-input
              v-model="updateForm.password2"
              class="el-input__medium"
            ></el-input>
          </el-form-item>
        </template>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleSure">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限配置 -->
    <el-dialog
      :close-on-click-modal="false"
      title="权限配置"
      :visible.sync="authDialog"
      width="90%"
    >
      <el-table
        v-loading="loading.menuTree"
        ref="multiTable"
        :data="menuTree"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column type="index" width="55">
          <template slot="header" slot-scope="scope">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="onCheckedChange($event, 'all')"
            ></el-checkbox>
          </template>
          <template slot-scope="scope">
            <el-checkbox
              v-model="scope.row.checked"
              @change="onCheckedChange($event, 'single', scope.row)"
            ></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" width="180"></el-table-column>
        <el-table-column align="center" label="类型" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type == 1">目录</el-tag>
            <el-tag v-if="scope.row.type == 2" type="success">菜单</el-tag>
            <el-tag v-if="scope.row.type == 3" type="warning">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="CODE" prop="code"> </el-table-column>
        <el-table-column label="URL" prop="url"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="authDialog = false">取 消</el-button>
        <el-button type="primary" @click="setRoleMenu">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 行政区域弹窗 -->
    <el-dialog
      title="行政区域"
      :visible.sync="zxRegionDialog"
      width="90%"
      :close-on-click-modal="false"
    >
      <el-table
        ref="Table"
        :data="zxRegionList"
        row-key="id"
        border
        @row-click="handleRowClick"
        @select="handSelTree"
        :class="typeFontClass"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="ID" prop="id"></el-table-column>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="邮编" prop="code">

        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="closeDia">关 闭</el-button>
        <el-button type="primary" @click="sureTree">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { requiredFormValidate } from "@/utils/validate.js";
import {
  sysrole_allList,
  setRoleMenu,
  selectMenuTreeByRoleId,
  sysuser_add,
  sysuser_delete,
  sysuser_resetPassword,
  sysuser_update,
  sysuser_list,
  sysuser_setOpen,
  selectAdminShangwuRegionTree,
  setShangwuRegion,
} from "@/api/platformSys";
import { sysDict_byType } from "@/api/dataDict";
import {jiaOrderCancelLiangfang, selectShangwuRegionTree} from "@/api/api";

const getDefaultForm = () => ({
  loginName: null,
  roleId: null,
  password: null,
  password2: null,
  remark: null,
  name: null,
  email: null,
  csBl: 100,
  fallbackUrl: null,
  accessKey: null,
  accessSecret: null,
  license: null,
  userType: null,
  companyName: null,
  bankName: null,
  bankNo: null,
  bankBranch: null,
  isPrizePool: null,
  phone: null,
  yaoqingma: null,
});

const getDefaultSearchBody = () => ({
  loginName: null,
  roleId: null,
});

export default {
  data() {
    const passwordValidate = (rule, value, callback) => {
      if (["", null].includes(value)) {
        callback(new Error("请输入"));
      } else if (this.updateForm.password != value) {
        callback(new Error("两次密码不一致"));
      } else {
        callback();
      }
    };
    const csBlValidate = (rule, value, callback) => {
      let findItem =
        this.roleIdOptions.find((d) => d.id == this.updateForm.roleId) || {};
      if (findItem.code === "business" && ["", null].includes(value)) {
        callback(new Error("请输入"));
      } else {
        callback();
      }
    };
    return {
      handleType: "",
      list: [],
      userTypeOpts: [],
      searchBody: getDefaultSearchBody(),
      loading: {
        list: true,
      },
      updateForm: getDefaultForm(),
      updateFormRule: {
        loginName: [
          { required: true, validator: requiredFormValidate, trigger: "blur" },
        ],
        roleId: [
          { required: true, validator: requiredFormValidate, trigger: "blur" },
        ],
        password: [
          { required: true, validator: requiredFormValidate, trigger: "blur" },
        ],
        password2: [
          { required: true, validator: passwordValidate, trigger: "blur" },
        ],
        csBl: [{ validator: csBlValidate, trigger: "blur" }],
      },
      pageNo: 1,
      pageSize: 20,
      totalCount: 0,
      pageSizeOpts: [20, 50, 100, 300, 500],
      updateDialog: false,

      roleIdOptions: [],
      // ----------------
      tmpRow: {},
      checkAll: false,
      isIndeterminate: false,
      menuTree: [],
      menuTreeDeep: 0,
      checkedCount: 0,
      authDialog: false,

      zxRegionList: [], //树的数据
      zxRegionDialog: false, // 树弹窗的显示隐藏
      lastTreeList: [], // 最后选中树
      shangwuId : null,
    };
  },
  created() {
    this.getData();
    this.getRoleList();
    this.getOptions();
  },
  methods: {
    typeFontClass({row, rowIndex}) {
      var type = row.type;
      if (type === 1) {
        return 'province-row';
      } else if(type === 2){
        return 'city-row';
      }else if(type === 3){
        return 'area-row';
      }
      return '';
    },
    closeDia() {
      this.zxRegionDialog = false;
    },
    sureTree() {
      // 确认选中
      var sysRegionIdList = [];
      this.lastTreeList.forEach(lastTreeItem =>{
        var id = lastTreeItem.id;
        sysRegionIdList.push(id);
      });

      this.$confirm(`确认设置该区域？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        setShangwuRegion({
          adminUserId: this.shangwuId,
          sysRegionIdList:sysRegionIdList
        }).then((res) => {
          this.$message.success(res.msg || "操作成功");
          this.getData();
          this.zxRegionDialog = false;

        });
      });
    },
    handleRowClick(row) {
      this.$refs.Table.toggleRowExpansion(row);
    },

    handSelTree(selection, val) {
      this.lastTreeList = selection;
    },

    getMenuTree(id, callback = () => {}) {
      selectMenuTreeByRoleId({
        id,
      }).then(({ result = {} }) => {
        this.menuTree = result.treeList;
        this.menuTreeDeep = result.treeSize;
        this.checkedCount = result.checkedSize;
        callback();
      });
    },
    getRoleList() {
      sysrole_allList().then((res) => {
        this.roleIdOptions = res.result;
      });
    },
    getData() {
      this.loading.list = true;
      sysuser_list({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        ...this.searchBody,
      }).then((res) => {
        this.list = res.result.data.map((d) => {
          d.isOpen = d.isOpen == 1;
          return d;
        });
        this.totalCount = res.result.totalCount;
        this.loading.list = false;
      });
    },
    getOptions() {
      sysDict_byType({
        dictType: "user_type_key",
      }).then((res) => {
        this.userTypeOpts = res.result;
      });
    },
    handleClick(type, row) {
      this.handleType = type;
      switch (type) {
        case "setRegion":
          // 商务行政区域设置
          this.zxRegionDialog = true;
          this.lastTreeList = [];
          this.shangwuId = row.id,
          this.getZxTreeData(row.id);

          break;
        case "add":
          this.updateDialog = true;
          /*getSccesskey().then((res) => {
            this.updateForm = Object.assign(getDefaultForm(), {
              accessKey: res.result.accessKey,
              accessSecret: res.result.accessSecret,
            });
          });*/
          this.$nextTick(() => {
            this.$refs.updateForm.clearValidate();
          });
          break;
        case "update":
          this.updateDialog = true;
          this.updateForm = Object.assign({}, row, {
            isOpen: row.isOpen ? 1 : 0,
          });
          this.$nextTick(() => {
            this.$refs.updateForm.clearValidate();
          });
          break;
        case "authSet":
          this.authDialog = true;
          this.tmpRow = row;
          this.getMenuTree(row.id, this.dealCheckAll);
          break;
        case "resetPwd":
          this.$confirm("此操作将重置该用户的密码, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            sysuser_resetPassword({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
            });
          });
          break;
        case "remove":
          this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            sysuser_delete({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
              this.getData();
            });
          });
          break;
        default:
          return;
      }
    },
    getZxTreeData(id) {
      selectAdminShangwuRegionTree({
        id: id,
      }).then(({ result }) => {
        this.zxRegionList = result || [];
        this.$nextTick( () => {
          this.zxRegionList.forEach(zxRegionItem => {
            var isShangwu =  zxRegionItem.isShangwu;
            if(isShangwu === 1){
              this.$refs.Table.toggleRowSelection (zxRegionItem,true);
            }
            var childrenList = zxRegionItem.children;
            this.$nextTick( () => {
              childrenList.forEach(children => {
                var isShangwu1 =  children.isShangwu;
                if(isShangwu1 === 1){
                  this.$refs.Table.toggleRowSelection (children,true);
                }
              });
            });
          });
        });

      });
    },
    handleSure() {
      let fn;
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          switch (this.handleType) {
            case "add":
              fn = sysuser_add;
              break;
            case "update":
              fn = sysuser_update;
              break;
            default:
              return;
          }
          const { password2, ...data } = this.updateForm;
          fn(data).then((res) => {
            this.updateDialog = false;
            this.$message.success(res.msg || "操作成功");
            this.getData();
          });
        } else {
          return false;
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getData();
    },
    onSwitchChange(flag, row) {
      this.$confirm(`是否要${flag == 1 ? "启用" : "冻结"}该用户？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        sysuser_setOpen({
          id: row.id
        }).then((res) => {
          row.isOpen = flag;
          this.$message.success(res.msg || "操作成功");
        });
      });
    },

    // table-改造

    toggleChecked(ary, flag) {
      return ary.map((item) => {
        return {
          ...item,
          checked: flag,
          children: this.toggleChecked(item.children || [], flag),
        };
      });
    },
    toggleChecked2(ary, flag) {
      ary.forEach((item) => {
        item.checked = flag;
        if (Array.isArray(item.children) && item.children.length > 0) {
          this.toggleChecked2(item.children, flag);
        }
      });
    },
    getCheckedCount(ary, sum = 0, ids = []) {
      let childrenSum;
      ary.forEach((item) => {
        if (item.checked) {
          sum++;
          ids.push(item.id);
        }
        if (Array.isArray(item.children) && item.children.length > 0) {
          childrenSum = this.getCheckedCount(item.children, 0, ids);
          sum += childrenSum;
        }
      });
      return sum;
    },
    onCheckedChange(flag, type, row) {
      switch (type) {
        case "all":
          this.menuTree = this.toggleChecked(this.menuTree, flag);
          this.isIndeterminate = false;
          break;
        case "single":
          this.toggleChecked2([row], flag);
          this.menuTree = JSON.parse(JSON.stringify(this.menuTree));
          this.dealCheckAll();
          break;
        default:
          return;
      }
    },
    dealCheckAll(initVal = null) {
      let checkedCount;
      if (initVal != null) {
        checkedCount = initVal;
      } else {
        checkedCount = this.getCheckedCount(this.menuTree); // 勾选个数等于列表总数，isIndeterminate为false
      }
      this.checkAll = checkedCount == this.menuTreeDeep;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.menuTreeDeep;
    },
    setRoleMenu() {
      const { id } = this.tmpRow;
      const sysMenuIdList = [];
      this.getCheckedCount(this.menuTree, 0, sysMenuIdList);
      setRoleMenu({
        id,
        sysMenuIdList,
      }).then((res) => {
        this.$message.success(res.msg || "操作成功");
        this.authDialog = false;
      });
    },

    onSearch() {
      this.pageNo = 1;
      this.getData();
    },
    onReset() {
      this.pageNo = 1;
      this.searchBody = getDefaultSearchBody();
      this.getData();
    },

    onUploadImgSuccess(res, file) {
      this.updateForm.license = file;
    },
  },
};
</script>
<style>
.el-table .province-row {
  font-size: 14px;
}

.el-table .city-row {
  font-size: 10px;
}

.el-table .area-row {
  background: rgba(235, 243, 249, 0.2);
}
</style>
